﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using App.Interface;
using Autofac;
using Autofac.Integration.Mvc;
using log4net.Config;

namespace App.MVC
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //应用程序启动时，自动加载配置log4Net  
            XmlConfigurator.Configure();
            AreaRegistration.RegisterAllAreas();
            var builder = RegisterServiceAutofac();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        private ContainerBuilder RegisterServiceAutofac()
        {
            var builder = new ContainerBuilder();
            var baseType = typeof(IDependency);
            var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList();
            builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();//属性注入
            #region 自动注入代码的实现
            builder.RegisterAssemblyTypes(assemblys.ToArray())
                .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
                .AsImplementedInterfaces().InstancePerLifetimeScope();
            #endregion
            return builder;
        }

    }
}
